package demo.netty.netty.http.subcribe_server;

import demo.netty.netty.http.entity.SubscribeReq;
import demo.netty.netty.http.entity.SubscribeResp;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class NettySubReqServer {


    public static void main(String[] args) {
        int port = 8080;
        new NettySubReqServer().bind(port);
    }


    public void bind(int port) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                .group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 100)
                .childHandler(new ChildChannelHandler());
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            //等待服务端监听端口关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }


    private static class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            //创建 WeakReferenceMap对类加载器进行缓存，支持多线程并发访问，当虚拟机内存不足时，会释放缓存中的内存，防止内存泄漏
            socketChannel.pipeline().addLast(
                new ObjectDecoder(1024 * 1024,
                                  ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
            socketChannel.pipeline().addLast(new ObjectEncoder());
            socketChannel.pipeline().addLast(new SubReqServerHandler());
        }
    }


    private static class SubReqServerHandler extends SimpleChannelInboundHandler<Object> {

        @Override
        public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
            SubscribeReq subscribeReq = (SubscribeReq) msg;
            if ("Lilinfeng".equalsIgnoreCase(subscribeReq.getUserName())) {
                System.out.println("Service accept client subscribe req : [" + subscribeReq.toString() + "]");
                ctx.writeAndFlush(resp(subscribeReq.getSubReqId()));
            }
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }

        private SubscribeResp resp(int subReqID) {
            SubscribeResp subscribeResp = new SubscribeResp();
            subscribeResp.setSubReqId(subReqID);
            subscribeResp.setRespCode(0);
            subscribeResp.setDesc("Netty book order succeed, 3 days later, sent to the designated address");
            return subscribeResp;
        }
    }



}
